package com.nowcoder.community.service;

import com.nowcoder.community.dao.CommonRedisDao;
import com.nowcoder.community.dao.EntityFollowDao;
import com.nowcoder.community.event.FollowEvent;
import com.nowcoder.community.event.producer.DefaultEventProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FollowService {
    @Autowired
    EntityFollowDao entityFollowDao;

    @Autowired
    CommonRedisDao commonRedisDao;

    @Autowired
    DefaultEventProducer defaultEventProducer;

    private void sendFollowEvent(int followerId, int userId) {
        defaultEventProducer.sendFollowEvent((FollowEvent) new FollowEvent()
                        .setFollowerId(followerId)
                        .setUserId(userId)
                        .setCreateTime(System.currentTimeMillis()));
    }

    public void followUser(int followerId, int userId) {
        entityFollowDao.followUser(followerId, userId);
        if (!commonRedisDao.hasFollowedHistory(followerId, userId)) {
            commonRedisDao.setUserFollowHistory(followerId, userId);
            sendFollowEvent(followerId, userId);
        }
    }

    public void unfollowUser(int followerId, int userId) {
        entityFollowDao.unfollowUser(followerId, userId);
    }

    public int countFollower(int userId) {
        return entityFollowDao.countFollower(userId);
    }

    public int countFollow(int userId) {
        return entityFollowDao.countFollow(userId);
    }

    public boolean isFollow(int followerId, int userId) {
        return entityFollowDao.isFollow(followerId, userId);
    }
}
